package com.shisfish.library.Controller;

import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import net.sf.json.JSONArray;

import com.shisfish.library.Impl.BookLendImpl;
import com.shisfish.library.Impl.BookLoanImpl;
import com.shisfish.library.Impl.EmailVerifyImpl;
import com.shisfish.library.Impl.RecordImpl;
import com.shisfish.library.Impl.UserImpl;
import com.shisfish.library.Impl.UserInterestImpl;
import com.shisfish.library.Impl.UtilImpl;
import com.shisfish.library.Model.EmailVerify;
import com.shisfish.library.Model.Record;
import com.shisfish.library.Model.User;
import com.shisfish.library.Model.UserInterest;
import com.shisfish.library.Model.Util;
import com.shisfish.library.Prere.Login;
import com.shisfish.library.Utils.CacheUtils;
import com.shisfish.library.Utils.DateFormatUtils;
import com.shisfish.library.Utils.EncryptUtils;
import com.shisfish.library.Utils.ExcelToBean;
import com.shisfish.library.Utils.JsonValueUtil;
import com.shisfish.library.Utils.LoginUtils;
import com.shisfish.library.Utils.RandomUtils;
import com.shisfish.library.Utils.SendEmailUtils;
import com.shisfish.library.Utils.FileUpload.FileUploadUtils;
import com.shisfish.library.Utils.FileUpload.FormJsonArrUtil;
import com.shisfish.library.Utils.Global.GlobalVariable;
import com.shisfish.library.Utils.Global.toJsonUtils;
import com.shisfish.library.Utils.PageModel.Page;
import com.shisfish.library.Utils.PageModel.PageUtils;

@Path("user")
public class UserController extends GlobalVariable {

	private UserImpl userImpl = new UserImpl();
	
	FileUploadUtils fileUploadUtils = new FileUploadUtils();
	
	JsonValueUtil jsonValueUtil = new JsonValueUtil();
	
	private BookLendImpl bookLendImpl = new BookLendImpl();
	
	private BookLoanImpl bookLoanImpl = new BookLoanImpl();
	
	private EmailVerifyImpl emailVerifyImpl = new EmailVerifyImpl();
	
	private RecordImpl recordImpl = new RecordImpl();
	
	private UserInterestImpl userInterestImpl = new UserInterestImpl();
	
	private UtilImpl utilImpl = new UtilImpl();
	
	/**
	 * @Author shisfish
	 * @Date 2015年12月31日 下午4:40:35
	 * @Descrition : 通过用户id修改用户信息
	 * @param employee
	 * @param request
	 * @return
	 */
	@POST
	@Path("updateAUser/{employee}")
	@Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON })
	@Produces(MediaType.TEXT_PLAIN)
	public String updateAUser(@PathParam("employee") String employee, @Context HttpServletRequest request) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		if (Login.isLoginUser(employee, request)) {
			
			// 取得所有文件和表单值
			JSONArray jsArr = fileUploadUtils.getRiverWayUpload(request);
			// 取得所有普通表单值
			JSONArray customjsArr = new FormJsonArrUtil().getFormJsonArr(jsArr, "form");
			// 获取form表单数据
			//String employee = jsonValueUtil.getValue(customjsArr, "employee");
			String username = jsonValueUtil.getValue(customjsArr, "username");
			String util = jsonValueUtil.getValue(customjsArr, "util");
			String department = jsonValueUtil.getValue(customjsArr, "department");
			String company = jsonValueUtil.getValue(customjsArr, "company");
			String address = jsonValueUtil.getValue(customjsArr, "address");//
			String qq = jsonValueUtil.getValue(customjsArr, "qq");//
			String wechat = jsonValueUtil.getValue(customjsArr, "wechat");
			String email = jsonValueUtil.getValue(customjsArr, "email");//
			String mobile_phone = jsonValueUtil.getValue(customjsArr,
					"mobile_phone");//
			String phone = jsonValueUtil.getValue(customjsArr, "phone");//
			String sexstr = jsonValueUtil.getValue(customjsArr, "sex");
			int sex = 0;
			if (!sexstr.isEmpty()) {
				sex = Integer.parseInt(sexstr);
			}
			int age = 0;
			String agestr = jsonValueUtil.getValue(customjsArr, "age");
			if (!agestr.isEmpty()) {
				age = Integer.parseInt(agestr);
			}
			String birthday = jsonValueUtil.getValue(customjsArr, "birthday");
			String loanid = jsonValueUtil.getValue(customjsArr, "loanid");;
			/*String password = jsonValueUtil.getValue(customjsArr, "password");;
			String ran = RandomUtils.getRandomString();*/
			int level = 0;
			String levelstr = jsonValueUtil.getValue(customjsArr, "level");
			if (!levelstr.isEmpty()) {
				level = Integer.parseInt(levelstr);
			}
			
			List<User> users = userImpl.selectByEmployee(employee);
			if (users.size() > 0) {
				User user = users.get(0);
				user.setAddress(address);
				user.setAge(age);
				user.setBirthday(birthday);
				user.setCompany(company);
				user.setDepartment(department);
				user.setEmail(email);
				user.setLevel(level);
				user.setLoanid(loanid);
				user.setMobile_phone(mobile_phone);
				user.setPhone(phone);
				user.setQq(qq);
				user.setSex(sex);
				user.setUsername(username);
				user.setUtil(util);
				user.setWechat(wechat);
				
				int flag = userImpl.updateOne(user);
				
				if (flag == 1) {
					globalMap.put(STATUS_CODE, SUCCESS);
				}
				else {
					globalMap.put(STATUS_CODE, UPDATE_WR);
				}
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
			
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2015年12月31日 下午4:40:22
	 * @Descrition : 用户登录
	 * @param userId
	 * @param password
	 * @param request
	 * @return
	 */
	@POST
	@Path("login")
	@Produces("application/json; charset=utf-8")
	public String login(@FormParam("userId") String userId,
			@FormParam("password") String password, 
			@Context HttpServletRequest request) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		List<User> users = userImpl.selectByUserId(userId);
 		
		//List<User> users = userImpl.selectByEmployee(employee);
		if (users.size() > 0) {
			User user = users.get(0);
			String pass = password;
			try {
				pass = EncryptUtils.getMD5(password + user.getRan());

				if (user.getPassword().equals(pass)) {
					user.setRecord(1);
					int flag = userImpl.updateOne(user);
					if (flag == 0) {
						globalMap.put(STATUS_CODE, UPDATE_WR);
					} else {
						globalMap.put(STATUS_CODE, SUCCESS);
						
						Cache cache = CacheUtils.getCache(USER_LOGIN, request);
						
						if (cache != null) {
							cache.put(new Element("employee", user.getEmployee()));
							cache.put(new Element(ISLOGIN, "1"));
						}

						if ("".equals(user.getEmail())) {
							globalMap.put("hasEmail", false);
						} else {
							globalMap.put("hasEmail", true);
						}
						globalMap.put("loanid", user.getLoanid());
						
						Calendar cal = Calendar.getInstance();
						cal.add(Calendar.DAY_OF_YEAR, 60);
						
						recordImpl.deleteByIDT(user.getEmployee(), 2);
						
						
						Record record = new Record(user.getEmployee(), cal.getTime(), 2);
						int flag_1 = recordImpl.insertOne(record);
						if (flag_1 == 0) {
							globalMap.put(STATUS_CODE, INSERT_WR);
						} else {
							List<Map<String, Object>> map = userImpl.selectUserId(userId);
							
							globalMap.put("employee", map.get(0));
							
						}
					}
				}
				else {
					globalMap.put(STATUS_CODE, LOGIN_WR);
				}

			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} 
		else if (users.size() == 0) {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		}
		else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}

		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2015年12月31日 下午4:40:07
	 * @Descrition : 用户修改密码
	 * @param userid
	 * @param passwordOld
	 * @param passwordNew
	 * @param request
	 * @return
	 */
	@POST
	@Path("changePass/{userid}")
	@Produces("application/json; charset=utf-8")
	public String changePass(@PathParam("userid") String userid,
			@FormParam("passwordOld") String passwordOld,
			@FormParam("passwordNew") String passwordNew, 
			@Context HttpServletRequest request) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		if (LoginUtils.isLoginUser(userid, request)) {
			String passOld = passwordOld;
			try {

				User user = userImpl.selectByEm(userid);
				
				if (user != null) {
					passOld = EncryptUtils
							.getMD5(passwordOld + user.getRan());

					// 才能进行改密码
					if (user.getPassword().equals(passOld)) {

						String passNew = EncryptUtils.getMD5(passwordNew
								+ user.getRan());

						user.setPassword(passNew);

						// 改了密码之后， 把登陆状态取消
						user.setRecord(0);

						int flag = userImpl.updateOne(user);

						if (flag == 0) {
							globalMap.put(STATUS_CODE, CHANGE_PASS_WR);
						} else {
							globalMap.put(STATUS_CODE, SUCCESS);
						}

					} else {
						globalMap.put(STATUS_CODE, PASS_WR);
					}
					
				} else {
					globalMap.put(STATUS_CODE, SELECT_EMPTY);
				}

			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}

		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2015年12月31日 下午4:39:39
	 * @Descrition : 通过用户id查找用户信息
	 * @param employee
	 * @return
	 */
	@POST
	@Path("selectByKey")
	@Produces("application/json; charset=utf-8")
	public String selectByKey(@FormParam("employee") String employee) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		//List<Map<String, Object>> users = userImpl.selectUserLessByEmployee(employee);
		List<User> users = userImpl.selectByEmployee(employee);
		if (users.size() > 0) {
			users.get(0).setPassword("");
			users.get(0).setRan("");
			globalMap.put(STATUS_CODE, SUCCESS);
			globalMap.put("user", users.get(0));
		}
		else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2015年12月31日 下午4:38:49
	 * @Descrition : 通过条件查询用户信息（分页）
	 * @param type
	 * @param choose
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@GET
	@Path("selectByCho/{type}/{choose}/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String selectByCho(@PathParam("type") String type, @PathParam("choose") String choose, 
			@PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		/**
		 * 1.借阅证：loanid
		 * 2.性别：sex
		 * 3.部门：department
		 * 4.姓名：username
		 * 5.员工号：userId
		 * 6.不选择（other）
		 */
		int count = 0;
		
		Page page = new Page();
		
		List<User> users = new ArrayList<User>();
		switch(type) {
			case "loanid" : 
				count = userImpl.countByLoanid(choose);
				if(count > 0){
					page = PageUtils.createPage(count, currentPage, pageSize);
					users = userImpl.selectByLoanidPage(choose, page.getBeginIndex(), pageSize);
				}
				break;
			case "sex" :
				count = userImpl.countBySex(Integer.parseInt(choose));
				if(count > 0){
					page = PageUtils.createPage(count, currentPage, pageSize);
					users = userImpl.selectBySexPage(choose, page.getBeginIndex(), pageSize);
				}
				break;
			case "util" :
				count = userImpl.countByUtil(choose);
				if(count > 0){
					page = PageUtils.createPage(count, currentPage, pageSize);
					users = userImpl.selectByUtilPage(choose, page.getBeginIndex(), pageSize);
				}
				break;
			case "username" :
				count = userImpl.countByUsername(choose);
				if(count > 0){
					page = PageUtils.createPage(count, currentPage, pageSize);
					users = userImpl.selectByUsernamePage(choose, page.getBeginIndex(), pageSize);
				}
				break;
			case "userId" :
				count = userImpl.countByUserId(choose);
				if(count > 0){
					page = PageUtils.createPage(count, currentPage, pageSize);
					users = userImpl.selectByUserIdPage(choose, page.getBeginIndex(), pageSize);
				}
				break;
			default :
				count = userImpl.countByCho(choose);
				if(count > 0){
					page = PageUtils.createPage(count, currentPage, pageSize);
					users = userImpl.selectByCho(choose, page.getBeginIndex(), pageSize);
				}
				break;
		}
		
		if (users.size() > 0) {
			globalMap.put("list", users);
			globalMap.put("page", page);
			globalMap.put(STATUS_CODE, SUCCESS);
		}
		else if (users.size() == 0) {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		}
		else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2015年12月31日 下午4:37:16
	 * @Descrition : 注销自己的账户
	 * @param employee
	 * @param request
	 * @return
	 */
	@GET
	@Path("cancelUser/{employee}")
	@Produces("application/json; charset=utf-8")
	public String cancelUser(@PathParam("employee") String employee, @Context HttpServletRequest request) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginUser(employee, request)) {
			List<User> users = userImpl.selectByEmployee(employee);
			
			if (users.size() > 0) {
				User user = users.get(0);
				user.setDeleteStatus(1);
				int flag = userImpl.updateOne(user);
				if (flag == 1) {
					globalMap.put(STATUS_CODE, SUCCESS);
				} else {
					globalMap.put(STATUS_CODE, UPDATE_WR);
				}
			} 
			else if (users.size() == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			}
			else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
			
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2015年12月31日 下午4:37:35
	 * @Descrition : 通过用户id查找用户借书记录（分页）
	 * @param employee
	 * @param request
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@GET
	@Path("lendLog/{employee}/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String lendLog(@PathParam("employee") String employee, @Context HttpServletRequest request, 
			@PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginUser(employee, request)) {
			
			int count = bookLendImpl.countByBorrower(employee);
			
			if (count > 0) {
				
				Page page = PageUtils.createPage(count, currentPage, pageSize);
				List<Map<String, Object>> books = bookLendImpl.selectByBorrower(employee, page.getBeginIndex(), pageSize);
				
				if (books.size() > 0) {
					globalMap.put("list", books);
					globalMap.put("page", page);
					globalMap.put(STATUS_CODE, SUCCESS);
				} else if (books.size() == 0) {
					globalMap.put(STATUS_CODE, SELECT_EMPTY);
				} else {
					globalMap.put(STATUS_CODE, SELECT_WR);
				}
				
			} else if (count == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
			
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2016年1月7日 下午6:44:02
	 * @Descrition : 通过用户id查找用户预约书记录（分页）
	 * @param employee
	 * @param request
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@GET
	@Path("loanLog/{employee}/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String loanLog(@PathParam("employee") String employee, @Context HttpServletRequest request, 
			@PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginUser(employee, request)) {
			
			int count = bookLoanImpl.countByLoaner(employee);
			
			if (count > 0) {
				
				Page page = PageUtils.createPage(count, currentPage, pageSize);
				List<Map<String, Object>> books = bookLoanImpl.selectByLoanerPage(employee, page.getBeginIndex(), pageSize);
				
				if (books.size() > 0) {
					globalMap.put("list", books);
					globalMap.put("page", page);
					globalMap.put(STATUS_CODE, SUCCESS);
				} else if (books.size() == 0) {
					globalMap.put(STATUS_CODE, SELECT_EMPTY);
				} else {
					globalMap.put(STATUS_CODE, SELECT_WR);
				}
				
			} else if (count == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
			
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2016年1月4日 下午4:20:49
	 * @Descrition : 邮箱发送修改密码
	 * @param employee
	 * @param email
	 * @param request
	 * @return
	 */
	@POST
	@Path("emailPasswordSend")
	@Produces("application/json; charset=utf-8")
	public String emailPasswordSend(@FormParam("email") String email, 
			@Context HttpServletRequest request) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		String to = email;
		String subject = "密码验证";
		String ran = RandomUtils.getRandomString(4);
		String content = "请输入以下验证码进行验证：" + ran;
		
		boolean flag = SendEmailUtils.sendAEmail(to, subject, content);
		
		if (flag) {
			globalMap.put(STATUS_CODE, SUCCESS);
			
			globalMap.put("ran", ran);
			
			globalMap.put("time", System.currentTimeMillis());
			
			globalMap.put("email", email);
		} else {
			globalMap.put(STATUS_CODE, SENDEMAIL_WR);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2016年1月4日 下午4:20:31
	 * @Descrition : 通过邮箱修改密码
	 * @param employee
	 * @param password
	 * @param request
	 * @return
	 */
	@POST
	@Path("emailPasswordChange1/{employee}")
	@Produces("application/json; charset=utf-8")
	public String emailPasswordChange1(@PathParam("employee") String employee, @FormParam("password") String password, 
			@Context HttpServletRequest request) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		List<User> users = userImpl.selectByEmployee(employee);
		
		if (users.size() > 0) {
			User user = users.get(0);
			String pass;
			try {
				pass = EncryptUtils.getMD5(password + user.getRan());
				user.setPassword(pass);
				user.setRecord(0);
				int flag = userImpl.updateOne(user);
				
				if (flag == 1) {
					globalMap.put(STATUS_CODE, SUCCESS);
				} else {
					globalMap.put(STATUS_CODE, CHANGE_PASS_WR);
				}
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				globalMap.put(STATUS_CODE, CHANGE_PASS_WR);
			}
			
		} else if (users.size() == 0) {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		} else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2016年1月7日 下午6:46:47
	 * @Descrition : 邮箱验证（发送）
	 * @param employee
	 * @param email
	 * @param request
	 * @return
	 */
	@POST
	@Path("emailVerifySend/{employee}")
	@Produces("application/json; charset=utf-8")
	public String emailVerifySend(@PathParam("employee") String employee, @FormParam("email") String email, 
			@FormParam("password") String password, @Context HttpServletRequest request) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginUser(employee, request)) {
			
			User user1 = userImpl.selectByEmail(email);
			
			if (user1 != null) {
				// 该邮箱已经有人在用
				globalMap.put(STATUS_CODE, SELECT_SAME);
			} else {
				// 验证密码
				User user = userImpl.selectByEm(employee);
				String ran = user.getRan();
				String pass = user.getPassword();
				
				try {
					String passStr = EncryptUtils.getMD5(password + ran);
					
					if (passStr.equals(pass)) {
						
						// 先把信息存入数据库
						emailVerifyImpl.deleteOneByKey(employee);
						
						String message = RandomUtils.getRandomString(4);
						
						Calendar cal = Calendar.getInstance();
						
						cal.add(Calendar.DAY_OF_YEAR, 1);
						
						EmailVerify emailVerify = new EmailVerify(email, employee, cal.getTime(), message);
						
						int flag = emailVerifyImpl.insertOne(emailVerify);
						
						if (flag == 1) {
							String to = email;
							String subject = "验证邮箱";

							String employeeStr = EncryptUtils.commonsCodesBase64Encoder(employee);
							
							String messageStr = EncryptUtils.commonsCodesBase64Encoder(message);
							
							String content = URL + "Library/library/user/emailVerifyGet?token=" + employeeStr + "_" + messageStr;
							
							boolean flag_1 = SendEmailUtils.sendAEmail(to, subject, "请点击一下连接进行邮箱验证:<br/>&nbsp;&nbsp;&nbsp;&nbsp;" + content);
							
							if (flag_1) {
								globalMap.put("str", content);
								globalMap.put(STATUS_CODE, SUCCESS);
							} else {
								globalMap.put(STATUS_CODE, SENDEMAIL_WR);
							}
							
						} else {
							globalMap.put(STATUS_CODE, INSERT_WR);
						}
					}
					else {
						globalMap.put(STATUS_CODE, PASS_WR);
					}
				} catch (NoSuchAlgorithmException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}

		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @author shisfish
	 * @date 2016年2月4日 下午2:39:07
	 * @Description 邮箱验证，接收
	 * @param token
	 * @return
	 */
	@GET
	@Path("emailVerifyGet")
	@Produces("application/json; charset=utf-8")
	public String emailVerifyGet(@QueryParam("token") String token) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		String[] tokens = token.split("_");
		
		String[] newTokens = new String[2];
		newTokens[0] = EncryptUtils.commonsCodesBase64Decoder(tokens[0]);
		newTokens[1] = EncryptUtils.commonsCodesBase64Decoder(tokens[1]);
		// 从数据库中取数据
		List<EmailVerify> emailVerifys = emailVerifyImpl.selectByKey(newTokens[0]);
		
		if (emailVerifys.size() > 0) {
			if (emailVerifys.get(0).getDeadline().before(new Date())) {
				globalMap.put(STATUS_CODE, OVER_DEADLINE);
			} else {
				String message = emailVerifys.get(0).getMessage();
				
				if (message.equals(newTokens[1])) {
					// 验证成功， 把邮箱加入用户数据中
					
					List<User> users = userImpl.selectByEmployee(newTokens[0]);
					if (users.size() > 0) {
						User user = users.get(0);
						user.setEmail(emailVerifys.get(0).getEmail());
						int flag = userImpl.updateOne(user);
						if (flag == 1) {
							globalMap.put(STATUS_CODE, SUCCESS);
						} else {
							globalMap.put(STATUS_CODE, UPDATE_WR);
						}
					} else if (users.size() == 0) {
						globalMap.put(STATUS_CODE, SELECT_WR);
					} else {
						globalMap.put(STATUS_CODE, SELECT_WR);
					}
					
				} else {
					// 验证失败，
					globalMap.put(STATUS_CODE, EMAILVERIFY_WR);
				}
			}
		} else if (emailVerifys.size() == 0) {
			globalMap.put(STATUS_CODE, SELECT_WR);
		} else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}	
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@GET
	@Path("emailPasswordGet/{email}")
	@Produces("application/json; charset=utf-8")
	public String emailPasswordGet(@PathParam("email") String email, @QueryParam("time") long time) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		Calendar cal = Calendar.getInstance();
		
		cal.add(Calendar.DAY_OF_YEAR, -1);
		
		long timeNow = cal.getTimeInMillis();
		
		long timeStamp = timeNow - time;
		
		if (timeStamp > 0) {
			globalMap.put(STATUS_CODE, OVER_DEADLINE);
		} else {
			globalMap.put(STATUS_CODE, SUCCESS);
			globalMap.put("time", time);
			globalMap.put("email", email);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @author shisfish
	 * @date 2016年2月4日 下午5:56:13
	 * @Description 修改密码（邮箱）
	 * @param email
	 * @param password
	 * @param time
	 * @return
	 */
	@POST
	@Path("emailPasswordChange")
	@Produces("application/json; charset=utf-8")
	public String emailPasswordChange(@FormParam("email") String email, @FormParam("password") String password, 
			@QueryParam("time") long time) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		Calendar cal = Calendar.getInstance();
		
		cal.add(Calendar.DAY_OF_YEAR, -1);
		
		long timeNow = cal.getTimeInMillis();
		
		long timeStamp = timeNow - time;
		
		if (timeStamp > 0) {
			globalMap.put(STATUS_CODE, OVER_DEADLINE);
		} else {
			
			User user = userImpl.selectByEmail(email);
			
			if (user != null) {
				String ran = user.getRan();
				
				if ("".equals(ran)) {
					ran = RandomUtils.getRandomString();
				}
				
				String pass = "";
				try {
					pass = EncryptUtils.getMD5(password + ran);
					user.setPassword(pass);
					user.setRecord(0);
					
					int flag = userImpl.updateOne(user);
					if (flag == 1) {
						globalMap.put(STATUS_CODE, SUCCESS);
					} else {
						globalMap.put(STATUS_CODE, UPDATE_WR);
					}
					
				} catch (NoSuchAlgorithmException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			}
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @author shisfish
	 * @date 2016年2月5日 下午10:56:21
	 * @Description 退出登录
	 * @param employee
	 * @param request
	 * @return
	 */
	@GET
	@Path("logout/{employee}")
	@Produces("application/json; charset=utf-8")
	public String logout(@PathParam("employee") String employee, @Context HttpServletRequest request) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginUser(employee, request)) {
			User user = userImpl.selectByEm(employee);
			if (user != null) {
				user.setRecord(0);
				int flag = userImpl.updateOne(user);
				if (flag == 1) {
					globalMap.put(STATUS_CODE, SUCCESS);
				} else {
					globalMap.put(STATUS_CODE, UPDATE_WR);
				}
			} else {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			}
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@POST
	@Path("excelInsert/{idadmin}")
	@Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON })
	@Produces(MediaType.TEXT_PLAIN)
	public String excelInsert(@PathParam("idadmin") String idadmin, @Context HttpServletRequest request)
			throws Exception {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		if (Login.isLoginAdmin(idadmin, request)) {
		
			String filePath = "d:\\";
	
			fileUploadUtils.setFilePath(filePath);
	
			// 取得所有文件和表单值 并保存文件至本地
			JSONArray jsArr = fileUploadUtils.getRiverWayUpload(request);
	
			// 获取文件
			JSONArray fileJsArr = new FormJsonArrUtil().getFormJsonArr(jsArr,
					"file");
	
			// 取得文件保存路径 "xxx" 为前台表单name 值必须一样
			String excelFilePath = filePath
					+ jsonValueUtil.getValue(fileJsArr, "userFile");
	
			// 将上传的表格转换成List
			String configFilePath = request.getSession().getServletContext()
					.getRealPath("/")
					+ File.separator + "excelModel/user.xml";
	
			List<User> users = new ArrayList<User>();
	
			ExcelToBean<User> util = new ExcelToBean<User>();
	
			try {
	
				// 判断文件格式是否正确
				users = util.parseExcelFileToBeans(new File(excelFilePath),
						new File(configFilePath));
				Util utils = utilImpl.getOne();
				for (User user : users) {
					Util uu = utilImpl.selectByName(user.getUtil());
					if (uu != null) {
						user.setUtil(uu.getId()+"");
					} else {
						user.setUtil(utils.getId() + "");;
					}
					
					String employee = "EM" + DateFormatUtils.getDateformat_1(new Date());
					user.setEmployee(employee);
					String ran = RandomUtils.getRandomString();
					String pass = EncryptUtils.getMD5("123456" + ran);
					user.setRan(ran);
					user.setPassword(pass);
					userImpl.insertOne(user);
					
					UserInterest userInterest = new UserInterest(employee, "", "", "");
					userInterestImpl.insertOne(userInterest);
				}
				
				System.out.println(users.size());
				
	
			} catch (Exception e) {
				globalMap.put("message", ADD_ERROR);
			}
		}

		return toJsonUtils.map2Json(globalMap);

	}
	
}
